'''
Author: @zhyy
Date: 2021-02-03 17:07:51
LastEditors: @zhyy
LastEditTime: 2021-02-03 18:19:29
'''
from app import db
class QueryToJson():
    # query结果转换为json格式
    @staticmethod
    def query_table_field_to_json_list(keys,result):
        '''
        description:查询表指定字段多条记录，转化为json格式 
        param  keys ["id,"uname","age"] result [(id1,name1,age1),(id2,name2,age2)]
        return [{"id":id1,"uname":name1,"age":age1}...]
        '''
        data=[]
        for values in result:
            data_dict= {k:v for k,v in zip(keys,values)}
            data.append(data_dict)
        return data
    
    @staticmethod
    def query_table_field_to_json(keys,result):
        '''
        description:查询表指定字段一条记录，转化为json格式 
        param  keys ["id,"uname","age"] result (id1,name1,age1)
        return {"id":id1,"uname":name1,"age":age1}
        '''
        data= {k:v for k,v in zip(keys,result)}
        return data
    @staticmethod
    def query_Single_table_to_json_list(result):
        '''
        description:查询表多条记录，转化为json格式 
        param  result [(id1,name1,age1),(id2,name2,age2)]
        return [{"id":id1,"uname":name1,"age":age1}...]
        '''
        data=[]
        for row in result:
            d={}
            for k,v in row.__dict__.items():
                if not k.startswith('_sa_instance_state'):
                    d[k]=v
            data.append(d)
        return data
    @staticmethod
    def query_Single_table_to_json(result):
        '''
        description:查询表一条记录，转化为json格式 
        param  result (id1,name1,age1)
        return {"id":id1,"uname":name1,"age":age1}
        '''
        data={}
        for k,v in result.__dict__.items():
            if not k.startswith('_sa_instance_state'):
                data[k]=v
        return data

    @staticmethod
    def query_page_Single_table(result):
        '''
        description: 分页查询整张表，转化为json
        param {*}
        return {*}
        '''        
        data={}
        for k,v in result.__dict__.items():
            if not k.startswith("query"):
                data[k]=v
        item=QueryToJson.query_Single_table_to_json_list(data.get("items"))
        data["items"]=item
        return data


    @staticmethod
    def query_page_field(keys,result):
        '''
        description:分页查询表字段转化为json 
        dict_items([
            ('query', <flask_sqlalchemy.BaseQuery object at 0x0000020ED9AE0850>), 
            ('page', 2), ('per_page', 2), ('total', 14), 
            ('items', [
                (10, '20210111_2Jwp4DZE'), (11, '20210111_CioQOfuY')
                ]
            )
            ])
        param {*}
        return {*}
        '''
        data={}
        for k,v in result.__dict__.items():
            if not k.startswith("query"):
                data[k]=v
        item=QueryToJson.query_table_field_to_json_list(keys,data.get("items"))
        data["items"]=item
        return data


        
   

        
